<?php 
namespace Home\Controller;
use Think\Controller;
class OrderController extends HomeController {
	/*
	 *总后台订单列表
	 *@page 请求的页面
	 */
	public function ordIndex()
	{
		$order=D('order');
		$result=$order->index();
		//获取支付方式
		$paytype=M('pay_ment')->where('isdisplay=0')->getField('id,name');
		//订单类型
		$areatype=M('config')->where('id=4')->getField('value');
		$areatype=unserialize($areatype);
		//获取订单状态(0未确认，2取消，1确认，3已付款，6配货中，8已发货，9已收货，4退货)
		$allstatus=M('config')->where('id=5')->getField('value');
		$allstatus=unserialize($allstatus);
		//所有加盟商家
		$allshop=M('shop_user')->getField('shopid,companyname');
        $pagearr=$result['pagearr'];
        $orders=$result['orders'];
        $this->assign('allstatus',$allstatus);
        $this->assign('allshop',$allshop);
        $this->assign('areatype',$areatype);
        $this->assign('paytype',$paytype);
        $this->assign('pagearr',$pagearr);
        $this->assign('orders',$orders);
        $this->display('index');
       

	}
	/*
	 * 编辑订单
	 * @param orderid
	 */
	public function editOrder(){
		$orderid=I('get.orderid',0 ,'strip_tags');
		$order=M('order a ');
		$orderdetail=$order->join('inner join '.C('DB_PREFIX').'order_item b on a.orderid=b.orderid')
		                   ->where(' b.orderid=%d',$orderid)
					       ->getField('a.orderid,a.order_sn,a.shopid,a.mobile,a.create_time ,a.pay_time, a.address,a.province,a.city,a.district,a.order_amount,a.consignee,a.deviceid,b.supperid,a.settlestatus,a.pay_type,a.shipping_status,a.pay_status,a.order_status,b.number,b.price,b.productid,b.itemname,b.specvale,a.deviceid,b.supperprice,b.activprice');
	    //计算订单状态
	    $orderstatus=intval($orderdetail[$orderid]['order_status'])+intval($orderdetail[$orderid]['pay_status'])+intval($orderdetail[$orderid]['shipping_status']);

	    //获取经销商信息
	   // $shopinfo=M('shop_user a')->where('shopid=%d',$shopid)->getField('shopid,companyname,address,mobile,telephone');
	    $devicecode=$orderdetail[$orderid]['deviceid'];
	    $shopinfo=M('shop_user a')->join("inner join ".C(DB_PREFIX).'device b on a.shopid=b.shopid')
	              ->where("b.devicecode='%s'", $devicecode)
	              ->getField('a.companyname');
	    //获取此订单供应商信息
	    $supperid=!empty($orderdetail[$orderid]['supperid'])?$orderdetail[$orderid]['supperid']:'';
	     $supperinfo=M('supper_user')->where('supperid=%d',$supperid)->getField('supperid,name,mobile,telephone,address,companyname,contactname');
	    $this->assign('shopinfo',$shopinfo);
	    $this->assign('supperinfo',$supperinfo[$supperid]);
	    $this->assign('order',$orderdetail[$orderid]);
	    $this->assign('orderstatus',$orderstatus);
		$this->display('detail');
	}
	/*
	 * 通过ajax 订单搜索
	 * @param 
	 * return json
	 */
	public function searchOrder()
	{
		$order=D('order');
		$result=$order->index();
		if(!empty($result['orders'])){
			$result['status']=1;
			echo json_encode($result,JSON_UNESCAPED_UNICODE);
			return '';

		}

		$result['status']=0;
		$result['message']='暂无数据';
		echo  json_encode($result,JSON_UNESCAPED_UNICODE);
	}
	/*
	 × 更改订单状态
	 * @param orderid
	 * return json
	 */
	public function orderStatus()
	{
		//获取需要改变的订单状态
		$result=array();
		$arg['status']=I('post.status',0,'strip_tags');
		$arg['orderid']=I('post.orderid',0, 'strip_tags');
		if(empty($arg['status']) || empty($arg['orderid']) )
		{
				$result['status']=0;
				$result['message']='参数错误';
				echo json_encode($result,JSON_UNESCAPED_UNICODE);
				return '';
		}
		//修改订单状态
		$orderModel=D('order');
		$temp=$orderModel->editStatus($arg);
		echo $temp;

	}
	//ajax 调用订单操作记录
	public function orderAction()
	{
		$result=array();
		$orderid=I('post.orderid',0,'strip_tags');
		$action=D('order');
		$temp=$action->orderLog($orderid);
		
		if (!empty($temp)) {
			$result['status']=1;
			$result['logs']=array_values($temp);
			echo json_encode($result,JSON_UNESCAPED_UNICODE);
		}else{
			$result['status']=0;
			echo json_encode($result,JSON_UNESCAPED_UNICODE);
		}
	}
	/*
	 *删除订单
	 *param orderid
	 *return json
	 */
	public function delOrder()
	{
		$orderid=I('get.orderid',0,'strip_tags');
		$orderid=intval($orderid);
		$where['orderid']=$orderid;
		//获取订单状态

		$temp=M()->query('select (order_status+pay_status+shipping_status) as status from '.C(DB_PREFIX).'order where orderid='.$orderid);
		$status=$temp[0]['status'];
		$status=intval($status);
		$order=M('order');
		$order_item=M('order_item');
		
		 //订单已取消
		$result=array();

		if ($status ===2)
		{
			

			//$order=$order->startTrans(); 事务支持有问题

			$result1=$order->where($where)->delete();
			$result2=$order_item->where($where)->delete();
			if ($result1 && $result2)
		    {
				//$order->commit();//删除成功
			    $result['status']=1;
			    $result['msg']='删除成功';
			    echo json_encode($result,JSON_UNESCAPED_UNICODE);
			    return '';
			}else{
				//$order->rollback();
				$result['status']=0;
			    $result['msg']='系统繁忙';
			    echo json_encode($result,JSON_UNESCAPED_UNICODE);
			    return '';
			}
		}
		$result['status']=0;
		$result['msg']='只有取消的订单可以删除';
		echo json_encode($result,JSON_UNESCAPED_UNICODE);
		return '';

	}	
	/*
	 * 导出订单
	 * @param  orderids 
	 * return csv
	 */
	public function putCsv(){
		$string=I('get.orderids','','strip_tags');
		$string=trim($string);
		$orderids=explode(',', $string);
		$where['a.orderid']= !empty($orderids)?array('in',$orderids):'';
		//获取订单基本信息
		$order=M('order a');
		$product=M('product');
		$item=M('item');
		$temp=$order->join('inner join '.C(DB_PREFIX).'order_item b on a.orderid=b.orderid')
					->where($where)
					->getField('a.orderid,a.order_sn,FROM_UNIXTIME(a.create_time, "%Y-%m-%d %H:%i:%S") as create_time,a.pay_type,b.itemname,b.brand,b.sn,b.specvale,b.number,a.order_amount,b.supperprice,b.price,a.shopid,a.consignee,a.mobile,a.province,a.city,a.district,a.address,b.itemid,b.productid,b.supperid');
		//获取商品库存
		foreach ($temp as $key =>&$value) {
			
			$value['alladdress']=$value['province'].$value['city'].$value['district'].$value['address'];

			if(!empty($value['productid'])){
				$value['inventory']=$product->where('productid=%d',$value['productid'])->getField('inventory');
			}else{
				$value['inventory']=$item->where('itemid=%d',$value['itemid'])->getField('inventory');
			}
			//计算毛利
			$value['grossprofit']=$value['price']-$value['supperprice'];
			$value['grossprofit']=round($value['grossprofit'],2);
			//计算毛利率
			$res=$value['grossprofit']/$value['price'];
			$value['grossmargin']=(round($res*100,2)).'%';
			//获取商家及运营商名称
			$value['shopname']=M('shop_user')->where('shopid=%d',$value['shopid'])->getField('companyname');
			$tp=M()->query('select companyname from '.C(DB_PREFIX).'yunying_user where yid=( select founder from '.C('DB_PREFIX').'shop_user where shopid= '.$value['shopid'].')');
			$value['yunname']=$tp[0]['companyname'];
			$value['pay_type']=!empty($value['pay_type'])?'支付宝支付':'银行转账';
			unset($value['shopid']);
			unset($value['itemid']);
			unset($value['productid']);
			unset($value['supperid']);
			unset($value['province']);
			unset($value['city']);
			unset($value['district']);
			unset($value['address']);
		}
		foreach ($temp as $key => &$value)
		{
			$value['order_sn']=$value['order_sn']."\t";
		}
		$csv=A('Home/Csv');
        $csv_title=array('序号','订单号','下单时间','支付方式','商品名称','商品品牌','商品型号','颜色','销售数量','销售金额','商品供价','商品售价','收货人','联系方式','收货地址','库存','毛利','毛利率','销售门店','所属运营商');
        $csv->put_csv($temp,$csv_title);
	}

}
